package com.atguigu.flink.window;

import com.atguigu.flink.function.WaterSensorMapFunction;
import com.atguigu.flink.pojo.WaterSensor;
import org.apache.flink.api.common.functions.AggregateFunction;
import org.apache.flink.configuration.Configuration;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.api.functions.windowing.ProcessAllWindowFunction;
import org.apache.flink.streaming.api.windowing.windows.GlobalWindow;
import org.apache.flink.util.Collector;

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.StreamSupport;

/**
 * Created by Smexy on 2023/11/14
       process做非滚动聚合
 */
public class Demo8_Process
{
    public static void main(String[] args) {

        Configuration conf = new Configuration();
        conf.setInteger("rest.port", 3333);
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment(conf);

                env
                   .socketTextStream("hadoop102", 8888)
                   .map(new WaterSensorMapFunction())
                    .countWindowAll(5l)
                    .process(new ProcessAllWindowFunction<WaterSensor, String, GlobalWindow>()
                    {
                        /*
                            Iterable<WaterSensor> elements: 窗口中收集的元素
                                process(): 窗口关闭时，只计算一次。
                                xxxWindowFunction： 窗口关闭时，只调动一次。
                         */
                        @Override
                        public void process(Context context, Iterable<WaterSensor> elements, Collector<String> out) throws Exception {
                            System.out.println("Demo8_Process.process");
                            List<WaterSensor> top3 = StreamSupport
                                .stream(elements.spliterator(), true)
                                .sorted((w1, w2) -> -w1.getVc().compareTo(w2.getVc()))
                                .limit(3)
                                .collect(Collectors.toList());

                            out.collect("vc top3:"+top3);
                        }
                    })
                    .print();


                try {
                            env.execute();
                        } catch (Exception e) {
                            e.printStackTrace();
                        }

    }
}
